/**
 * 设置管理器 - 统一管理用户设置的持久化
 * 负责设置的保存、加载、导入、导出和重置功能
 */
class SettingsManager {
    constructor() {
        this.storageKey = 'pomodoroSettings';
        this.defaultSettings = {
            // 时间设置
            timers: {
                work: { hours: 0, minutes: 25, seconds: 0 },
                shortBreak: { hours: 0, minutes: 5, seconds: 0 },
                longBreak: { hours: 0, minutes: 15, seconds: 0 },
                longBreakInterval: 4
            },
            // 功能开关
            features: {
                enableShortBreak: true,
                enableLongBreak: true
            },
            // 音频设置
            audio: {
                enabled: true,
                soundType: 'bell',
                volume: 80
            },
            // 主题设置
            theme: {
                colorScheme: 'default',
                fontSize: 'medium',
                darkMode: false,
                progressStyle: 'classic'
            },
            // 统计数据
            statistics: {
                totalPomodoros: 0,
                totalFocusTime: 0, // 分钟
                dailyStats: {},
                weeklyStats: {},
                monthlyStats: {}
            },
            // 应用设置
            app: {
                version: '2.0.0',
                lastUsed: new Date().toISOString(),
                firstInstall: new Date().toISOString()
            }
        };
        
        this.listeners = [];
        this.init();
    }
    
    /**
     * 初始化设置管理器
     */
    init() {
        // 检查本地存储是否可用
        if (!this.isStorageAvailable()) {
            console.warn('LocalStorage not available, settings will not persist');
            return;
        }
        
        // 加载现有设置
        this.loadSettings();
        
        // 监听页面卸载事件，确保设置被保存
        window.addEventListener('beforeunload', () => {
            this.saveSettings();
        });
        
        console.log('SettingsManager initialized');
    }
    
    /**
     * 检查本地存储是否可用
     */
    isStorageAvailable() {
        try {
            const test = '__storage_test__';
            localStorage.setItem(test, test);
            localStorage.removeItem(test);
            return true;
        } catch (e) {
            return false;
        }
    }
    
    /**
     * 加载设置
     */
    loadSettings() {
        try {
            const stored = localStorage.getItem(this.storageKey);
            if (stored) {
                const parsedSettings = JSON.parse(stored);
                // 合并默认设置和存储的设置，确保新增的设置项有默认值
                this.settings = this.mergeSettings(this.defaultSettings, parsedSettings);
                
                // 更新最后使用时间
                this.settings.app.lastUsed = new Date().toISOString();
            } else {
                // 首次使用，使用默认设置
                this.settings = JSON.parse(JSON.stringify(this.defaultSettings));
            }
        } catch (error) {
            console.error('Failed to load settings:', error);
            this.settings = JSON.parse(JSON.stringify(this.defaultSettings));
        }
        
        this.notifyListeners('load');
    }
    
    /**
     * 深度合并设置对象
     */
    mergeSettings(defaultSettings, userSettings) {
        const merged = JSON.parse(JSON.stringify(defaultSettings));
        
        function deepMerge(target, source) {
            for (const key in source) {
                if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
                    if (!target[key]) target[key] = {};
                    deepMerge(target[key], source[key]);
                } else {
                    target[key] = source[key];
                }
            }
        }
        
        deepMerge(merged, userSettings);
        return merged;
    }
    
    /**
     * 保存设置
     */
    saveSettings() {
        if (!this.isStorageAvailable()) {
            console.warn('Cannot save settings: LocalStorage not available');
            return false;
        }
        
        try {
            // 更新最后使用时间
            this.settings.app.lastUsed = new Date().toISOString();
            
            localStorage.setItem(this.storageKey, JSON.stringify(this.settings));
            this.notifyListeners('save');
            console.log('Settings saved successfully');
            return true;
        } catch (error) {
            console.error('Failed to save settings:', error);
            return false;
        }
    }
    
    /**
     * 获取设置值
     */
    get(path) {
        const keys = path.split('.');
        let value = this.settings;
        
        for (const key of keys) {
            if (value && typeof value === 'object' && key in value) {
                value = value[key];
            } else {
                return undefined;
            }
        }
        
        return value;
    }
    
    /**
     * 设置值
     */
    set(path, value) {
        const keys = path.split('.');
        let target = this.settings;
        
        // 导航到目标对象
        for (let i = 0; i < keys.length - 1; i++) {
            const key = keys[i];
            if (!target[key] || typeof target[key] !== 'object') {
                target[key] = {};
            }
            target = target[key];
        }
        
        // 设置值
        const lastKey = keys[keys.length - 1];
        target[lastKey] = value;
        
        // 自动保存
        this.saveSettings();
        this.notifyListeners('change', { path, value });
    }
    
    /**
     * 获取所有设置
     */
    getAll() {
        return JSON.parse(JSON.stringify(this.settings));
    }
    
    /**
     * 导出设置为JSON文件
     */
    exportSettings() {
        try {
            const exportData = {
                version: this.settings.app.version,
                exportDate: new Date().toISOString(),
                settings: this.getAll()
            };
            
            const dataStr = JSON.stringify(exportData, null, 2);
            const dataBlob = new Blob([dataStr], { type: 'application/json' });
            
            // 创建下载链接
            const link = document.createElement('a');
            link.href = URL.createObjectURL(dataBlob);
            link.download = `pomodoro-settings-${new Date().toISOString().split('T')[0]}.json`;
            
            // 触发下载
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 清理URL对象
            URL.revokeObjectURL(link.href);
            
            console.log('Settings exported successfully');
            return true;
        } catch (error) {
            console.error('Failed to export settings:', error);
            return false;
        }
    }
    
    /**
     * 导入设置从JSON文件
     */
    importSettings(file) {
        return new Promise((resolve, reject) => {
            if (!file || file.type !== 'application/json') {
                reject(new Error('请选择有效的JSON文件'));
                return;
            }
            
            const reader = new FileReader();
            
            reader.onload = (e) => {
                try {
                    const importData = JSON.parse(e.target.result);
                    
                    // 验证导入数据格式
                    if (!importData.settings || !importData.version) {
                        throw new Error('无效的设置文件格式');
                    }
                    
                    // 合并导入的设置
                    const importedSettings = this.mergeSettings(this.defaultSettings, importData.settings);
                    
                    // 保留当前的统计数据（可选）
                    const keepStats = confirm('是否保留当前的统计数据？点击"确定"保留，点击"取消"使用导入文件的数据。');
                    if (keepStats) {
                        importedSettings.statistics = this.settings.statistics;
                    }
                    
                    // 更新应用信息
                    importedSettings.app.lastUsed = new Date().toISOString();
                    importedSettings.app.version = this.defaultSettings.app.version;
                    
                    // 应用新设置
                    this.settings = importedSettings;
                    this.saveSettings();
                    
                    this.notifyListeners('import');
                    console.log('Settings imported successfully');
                    resolve(true);
                } catch (error) {
                    console.error('Failed to import settings:', error);
                    reject(error);
                }
            };
            
            reader.onerror = () => {
                reject(new Error('文件读取失败'));
            };
            
            reader.readAsText(file);
        });
    }
    
    /**
     * 重置设置到默认值
     */
    resetSettings(keepStatistics = false) {
        try {
            const newSettings = JSON.parse(JSON.stringify(this.defaultSettings));
            
            // 可选择保留统计数据
            if (keepStatistics && this.settings.statistics) {
                newSettings.statistics = this.settings.statistics;
            }
            
            this.settings = newSettings;
            this.saveSettings();
            
            this.notifyListeners('reset');
            console.log('Settings reset to default');
            return true;
        } catch (error) {
            console.error('Failed to reset settings:', error);
            return false;
        }
    }
    
    /**
     * 添加设置变化监听器
     */
    addListener(callback) {
        this.listeners.push(callback);
    }
    
    /**
     * 移除设置变化监听器
     */
    removeListener(callback) {
        const index = this.listeners.indexOf(callback);
        if (index > -1) {
            this.listeners.splice(index, 1);
        }
    }
    
    /**
     * 通知所有监听器
     */
    notifyListeners(event, data = null) {
        this.listeners.forEach(callback => {
            try {
                callback(event, data, this.settings);
            } catch (error) {
                console.error('Settings listener error:', error);
            }
        });
    }
    
    /**
     * 获取存储使用情况
     */
    getStorageInfo() {
        if (!this.isStorageAvailable()) {
            return null;
        }
        
        try {
            const settingsSize = new Blob([JSON.stringify(this.settings)]).size;
            const totalUsed = JSON.stringify(localStorage).length;
            
            return {
                settingsSize: settingsSize,
                totalUsed: totalUsed,
                settingsSizeFormatted: this.formatBytes(settingsSize),
                totalUsedFormatted: this.formatBytes(totalUsed)
            };
        } catch (error) {
            console.error('Failed to get storage info:', error);
            return null;
        }
    }
    
    /**
     * 格式化字节大小
     */
    formatBytes(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    /**
     * 清理过期的统计数据（保留最近30天）
     */
    cleanupOldStatistics() {
        try {
            const thirtyDaysAgo = new Date();
            thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
            
            const dailyStats = this.settings.statistics.dailyStats || {};
            const cleanedStats = {};
            
            for (const [date, stats] of Object.entries(dailyStats)) {
                if (new Date(date) >= thirtyDaysAgo) {
                    cleanedStats[date] = stats;
                }
            }
            
            this.settings.statistics.dailyStats = cleanedStats;
            this.saveSettings();
            
            console.log('Old statistics cleaned up');
            return true;
        } catch (error) {
            console.error('Failed to cleanup old statistics:', error);
            return false;
        }
    }
}

// 导出设置管理器
if (typeof module !== 'undefined' && module.exports) {
    module.exports = SettingsManager;
}